﻿using UnityEngine;
using UnityEngine.EventSystems;

namespace JH
{
    /// <summary>
    /// 排序射线投射结果
    /// </summary>
    public static class SortResultRealization
    {
        /// <summary>
        /// 投射结果排序，这段代码是从源码里复制出来的
        /// </summary>
        public static int RaycastComparerEm(this BaseRaycaster _, RaycastResult lhs, RaycastResult rhs)
        {
            return RaycastComparer(lhs, rhs);
        }

        /// <summary>
        /// 投射结果排序，这段代码是从源码里复制出来的
        /// </summary>
        public static int RaycastComparer(RaycastResult lhs, RaycastResult rhs)
        {
            if (lhs.module != rhs.module)
            {
                var lhsEventCamera = lhs.module.eventCamera;
                var rhsEventCamera = rhs.module.eventCamera;
                if (lhsEventCamera != null && rhsEventCamera != null &&
                    Mathf.Approximately(lhsEventCamera.depth, rhsEventCamera.depth))
                {
                    // need to reverse the standard compareTo
                    if (lhsEventCamera.depth < rhsEventCamera.depth)
                        return 1;
                    if (Mathf.Approximately(lhsEventCamera.depth, rhsEventCamera.depth))
                        return 0;

                    return -1;
                }

                if (lhs.module.sortOrderPriority != rhs.module.sortOrderPriority)
                    return rhs.module.sortOrderPriority.CompareTo(lhs.module.sortOrderPriority);

                if (lhs.module.renderOrderPriority != rhs.module.renderOrderPriority)
                    return rhs.module.renderOrderPriority.CompareTo(lhs.module.renderOrderPriority);
            }

            if (lhs.sortingLayer != rhs.sortingLayer)
            {
                // Uses the layer value to properly compare the relative order of the layers.
                var rid = SortingLayer.GetLayerValueFromID(rhs.sortingLayer);
                var lid = SortingLayer.GetLayerValueFromID(lhs.sortingLayer);
                return rid.CompareTo(lid);
            }

            if (lhs.sortingOrder != rhs.sortingOrder)
                return rhs.sortingOrder.CompareTo(lhs.sortingOrder);

            // comparing depth only makes sense if the two raycast results have the same root canvas (case 912396)
            if (lhs.depth != rhs.depth && lhs.module.rootRaycaster == rhs.module.rootRaycaster)
                return rhs.depth.CompareTo(lhs.depth);

            if (Mathf.Approximately(lhs.distance, rhs.distance))
                return lhs.distance.CompareTo(rhs.distance);

            return lhs.index.CompareTo(rhs.index);
        }
    }
}